﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ComponentModel;
using System.Globalization;
using System.Xml.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Advertising.Mobile.UI;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using MarkHeath.StarRating;
using OnlineVideos.ViewModels;
using Common.Library;
using OnlineVideos.Library;
using OnlineVideos.UI;
using OnlineVideos.Common;
using OnlineVideos.View_Models;
using OnlineVideos.Entities;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Threading;
//using OnlineVideos.Game;
//using MyToolkit.Multimedia;
using OnlineVideos.Data;
using OnlineVideos.Utilities;
using Common.Utilities;
using PicasaMobileInterface;
using System.Threading.Tasks;

namespace World_Dance.Views
{
    public partial class DanceDetailPage : PhoneApplicationPage
    {
        string background = "0";
        string chapter = string.Empty;
        public DispatcherTimer storyboardtimer;
        bool appbarvisible = true;
        string navigationvalue = string.Empty;
        PivotItem currentItem = default(PivotItem);
        string pivotindex = string.Empty;

        private void LoadPivotThemes(long ShowID)
        {
            pvtMainDetails.Background = ShowDetail.LoadShowPivotBackground(ShowID);

            Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded);
        }

        public DanceDetailPage()
        {
            InitializeComponent();
            if (AppSettings.ShowID != "0")
            {
                LoadPivotThemes(AppSettings.ShowUniqueID);
                //TODO: Save title also in settings or pass through query string
                tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
                background = "1";
            }
            Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded);
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(MainGrid, adstaSongs, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            LoadAds();
            FlurryWP8SDK.Api.LogEvent("DanceDetailPage", true);
            int showid = AppSettings.ShowUniqueID;
            string sharedstatus = Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.ShareStatus;
            if (sharedstatus == "Shared To Blog")
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Shared To Blog)";
            else
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Not Shared)";
            performanceProgressBar.IsIndeterminate = true;

            string id = "";
            if (NavigationContext.QueryString.TryGetValue("id", out id))
                AppSettings.ShowID = id;

            if (background == "0")
            {
                LoadPivotThemes(AppSettings.ShowUniqueID);
                tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
            }
            performanceProgressBar.IsIndeterminate = false;
            PageHelper.RemoveEntryFromBackStack("DanceDetailPage");
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            FlurryWP8SDK.Api.LogPageView();
          
            int showid = AppSettings.ShowUniqueID;
            if (Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync().Result.Status != "Custom")
            {
                this.ApplicationBar.IsVisible = false;
                appbarvisible = false;
            }
            else
            {
                this.ApplicationBar.IsVisible = true;
            }
            if (NavigationContext.QueryString.TryGetValue("navigationvalue", out navigationvalue))
            {

                if (navigationvalue == "1")
                {
                    if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                        pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                    Constants.navigationvalue++;
                }
                else
                {
                    if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                        pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                    Constants.navigationvalue--;
                }
                while (NavigationService.BackStack.Count() > 1)
                {
                    if (!NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("DanceDetailPage"))
                    {
                        NavigationService.RemoveBackEntry();
                    }
                    else
                    {
                        NavigationService.RemoveBackEntry();
                        break;
                    }
                }
            }
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                AppState.searchtitle = "";
            }
            else
            {
                if (NavigationContext.QueryString.TryGetValue("chapter", out chapter))
                {

                    AppState.searchtitle = chapter;
                }
            }

            if (VideosList.lbxSongsList.IsEnabled == false)
                VideosList.lbxSongsList.IsEnabled = true;
            //YouTube.CancelPlay();
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            FlurryWP8SDK.Api.EndTimedEvent("DanceDetailPage");
            AppState.searchtitle = "";
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            //if (YouTube.CancelPlay())
            //    e.Cancel = true;

            base.OnBackKeyPress(e);
        }

        private void imgTitle_MouseEnter(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        private void pvtMainDetails_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            currentItem = e.AddedItems[0] as PivotItem;
            if (appbarvisible == true)
            {
                if (currentItem != null)
                {
                    if (currentItem.Header.ToString() == "detail")
                    {
                        if (this.ApplicationBar.MenuItems.Count == 2)
                            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Edit" + " " + "description";
                        else
                        {
                            ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Edit" + " " + "description");
                            appBarMenuitem.Click += btnadd_Click_1;
                            this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                        }

                    }

                    else
                    {
                        if (this.ApplicationBar.MenuItems.Count < 2)
                        {
                            ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Add" + " " + currentItem.Header.ToString());
                            appBarMenuitem.Click += btnadd_Click_1;
                            this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                        }
                        else
                        {
                            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add" + " " + currentItem.Header.ToString();
                        }
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;

                    }
                }
            }
        }
        private void btnadd_Click_1(object sender, EventArgs e)
        {

            if ((sender as ApplicationBarMenuItem).Text.Contains("videos"))
            {
                Constants.DownloadTimer.Stop();
                Constants.Linkstype = "Songs";
                NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + string.Empty, UriKind.Relative));
            }
            else if ((sender as ApplicationBarMenuItem).Text.Contains("description"))
            {
                Constants.DownloadTimer.Stop();
                Constants.editdescription = true;
                NavigationService.Navigate(new Uri("/Views/Description.xaml", UriKind.RelativeOrAbsolute));
            }

        }

        private void btnshare_Click_1(object sender, EventArgs e)
        {
            if (NetworkHelper.IsNetworkAvailableForDownloads())
            {
                UploadToBlog upload = new UploadToBlog(AppSettings.ShowUniqueID, page1: this);
            }
        }


    }
}